package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        System.out.println("开始注册~");
        Scanner scan=new Scanner(System.in);
        System.out.println("请输入用户名！");
        String userName=scan.nextLine();
        System.out.println("请输入密码！");
        String passWord=scan.nextLine();
        System.out.println("请输入昵称！");
        String nickName=scan.nextLine();
        System.out.println("请输入年龄！");
        int age=scan.nextInt();
        scan.nextLine();
        try(Connection connection=DBUtil.getConnextion("tedu")) {
            String sql1="select username from userinfo where username=?";
            PreparedStatement ps1=connection.prepareStatement(sql1);
            ps1.setString(1,userName);
            ResultSet r1=ps1.executeQuery();
            if (r1.next()){
                System.out.println("用户名已存在！请重新输入！");
            }else{
                String sql2="insert into userinfo(username,password,nickname,age) values(?,?,?,?)";
                PreparedStatement ps2=connection.prepareStatement(sql2);
                ps2.setString(1,userName);
                ps2.setString(2,passWord);
                ps2.setString(3,nickName);
                ps2.setInt(4,age);
                int i=ps2.executeUpdate();
                if (i>0){
                    System.out.println("注册成功！");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
